package backend.server;

import backend.core.tbm.TableManager;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;


public class App {
    // TODO 读取配置
    private int port;

    TableManager tbm;

    public App(int port, TableManager tbm) {
        this.port = port;
        this.tbm = tbm;
    }

    //Server 启动一个 ServerSocket 监听端口，当有请求到来时直接把请求丢给一个新线程处理
    public void start() {

        EventLoopGroup bossGroup = new NioEventLoopGroup(1);
        EventLoopGroup workerGroup = new NioEventLoopGroup();

        try {
            System.out.println("Server listen to port: " + port);

            ServerBootstrap bootStrap = new ServerBootstrap();
            bootStrap.group(bossGroup, workerGroup);
            bootStrap.channel(NioServerSocketChannel.class);

            bootStrap.childHandler(new ChannelInitializer<SocketChannel>() {
                @Override
                protected void initChannel(SocketChannel socketChannel) throws Exception {
                    ChannelPipeline pipeline = socketChannel.pipeline();

                    pipeline.addLast("decoder", new LiveDecoder());
                    pipeline.addLast("encoder", new LiveEncoder());
                    pipeline.addLast(new ServerHandler(tbm));
                }
            });
            bootStrap.option(ChannelOption.SO_BACKLOG, 1024);
            bootStrap.childOption(ChannelOption.SO_KEEPALIVE, Boolean.TRUE);

            ChannelFuture channelFuture = bootStrap.bind(port).sync();
            channelFuture.channel().closeFuture().sync();
//            channelFuture.sync();

            channelFuture.addListener(future -> {
                if (future.isSuccess()) {
                    System.out.println("ChannelFuture：关闭成功");
                } else {
                    System.out.println("ChannelFuture：关闭失败");
                }

            });

        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        } finally {
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }
//
    }
}
